<template>
    <label>
        <span>
            <input 
            type="radio"
            :disabled="disabled"
            :checked="currentValue"
            @change="change"
            />
        </span><slot>{{label}}</slot>
    </label>
</template>

<script>
import {findComponentUpward,oneOf} from '@/utils/assist';
import Emitter from 'common/mixins/emitter'
export default {
    name:'iRadio',
    mixins:[Emitter],
    props:{
        value:{
            type:[String,Number,Boolean],
            default:false
        },
        trueValue:{
            type:[String,Number,Boolean],
            default:true
        },
        falseValue:{
            type:[String,Number,Boolean],
            default:false
        },
        label:{
            type:[String,Number]
        },
        disabled:{
            type:Boolean,
            default:false
        }
    },
    data() {
        return {
            currentValue:this.value,
            group:false, 
            parent:findComponentUpward(this,'iRadioGroup'),
            focusWrapper:false,
            focusInner:false
        }
    },
    methods:{
        change(event) {
            if(this.disabled) {
                return false;
            }
            
            const checked = event.target.checked;
            console.log(checked)
            this.currentValue = checked;
            const value = checked?this.trueValue:this.falseValue;

            this.$emit('input',value);

            if(this.group) {
                if(this.label!==undefined) {
                    this.parent.change({
                        value:this.label,
                        checked:this.value
                    });
                }
            } else {
                this.$emit('on-change',value);
                this.dispatch('FormItem','on-form-change',value);
            }
        },
        updateValue() {
            this.currentValue = this.value === this.trueValue;
        },
        onBlur() {
            this.focusWrapper = false;
            this.focusInner = false;
        },
        onFocus() {
            if(this.group && this.parent.type === 'button') {
                this.focusWrapper = true;
            } else {
                this.focusInner = true;
            }
        }
    },
    mounted() {
        if(this.parent) {
            this.group= true;
        }
        if(this.group) {
            this.parent.updateValue()
        } else {
            this.updateValue();
        }

    },
    watch:{
        value(val) {
            if(val === this.trueValue || val === this.falseValue ) {
                this.updateValue();
            } else {
                throw 'Value should be trueValue or falseValue'
            }
        }
    }
}
</script>

<style>

</style>
